package com.example.waimai.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.example.waimai.context.AliPayProperties;
import com.example.waimai.pojo.AliPayBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AliPayUtil {

    @Autowired
    private AliPayProperties aliPayProperties;
    /*
    * 通过 支付宝的SDK 生成 OrderInfo 返回给App
    * */
    public String getOrderInfo(AliPayBean aliPayBean){
        /*
        可以看到： 需要网关 ， APPID ,秘钥，json,编码格式,公钥，加密类型
        * */
        String app_id = aliPayProperties.getAPP_ID();
        String charset = aliPayProperties.getCHARSET();
        String gateway_url = aliPayProperties.getGATEWAY_URL();
        String privary_key = aliPayProperties.getPRIVARY_KEY();
        String public_key = aliPayProperties.getPUBLIC_KEY();
        String sign_type = aliPayProperties.getSIGN_TYPE();
        String format = "json";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway_url, app_id, privary_key, format, charset, public_key, sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // 封装订单信息
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(aliPayBean.getBody());// 商品描述
        model.setSubject(aliPayBean.getSubject());
        model.setOutTradeNo(aliPayBean.getOut_trade_no()); // 订单号
        model.setTimeoutExpress("30m");
        model.setTotalAmount(aliPayBean.getTotal_amount()); // 总金额
        model.setProductCode(aliPayBean.getProduct_code());
        request.setBizModel(model);
        request.setNotifyUrl("http://121.196.42.169:8888/notifyurl");
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";
    }

}
